package net.jxtz.jxtzos.controller.cdfile;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.cdfile.FileServiceImpl;
import net.jxtz.jxtzos.entity.cdfile.CdFile;
import net.jxtz.jxtzos.entity.web.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author a123
 */

@RestController
@CrossOrigin
@RequestMapping("/cd_file")
@Slf4j
public class CdFileController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R add(@RequestBody CdFile cdFile){
        boolean newFolder = fileServiceImpl.createNewFolder(cdFile);
        return newFolder ? R.ok():R.error();
    }

    @SneakyThrows
    @RequestMapping(value = "/upload_file", method = RequestMethod.POST)
    public R uploadFile(MultipartFile file, HttpServletRequest request) {
        fileServiceImpl.addFile(URLDecoder.decode(request.getHeader("filePath"), "UTF-8"), file);
        return R.ok();
    }

    @RequestMapping(value = "/upload_dir", method = RequestMethod.POST)
    public R uploadDir(@RequestParam("dir") MultipartFile[] dir , @RequestParam Map<String, Object> filePath){
        fileServiceImpl.addFiles(filePath.get("filePath").toString(), dir);
        return R.ok();
    }

    @RequestMapping(value = "/delete_file", method = RequestMethod.POST)
    public R delete(@RequestBody List<CdFile> cdFiles) {
        fileServiceImpl.deleteFiles(cdFiles);
        return R.ok();
    }

    @SneakyThrows
    @RequestMapping(value = "/download_file", method = RequestMethod.POST)
    public void downloadFile(@RequestBody CdFile file, HttpServletResponse response){
        String fileName = "";
        if (file.getFileStatus() == 0){
            fileName = URLEncoder.encode(file.getFileName().substring(file.getFileName().lastIndexOf(".")), "UTF-8").replaceAll("\\+", "%20");
        }else {
            fileName = file.getFileName();
        }
        HttpServletResponse responseHeaderSet = fileDownloadResponseHeaderSet(fileName, response);
        fileServiceImpl.downloadFile(file, responseHeaderSet.getOutputStream(), true);
    }

    @SneakyThrows
    @RequestMapping(value = "/download_files", method = RequestMethod.POST)
    public void downloadFiles(@RequestBody List<CdFile> cdFiles, HttpServletResponse response){
        HttpServletResponse responseHeaderSet = fileDownloadResponseHeaderSet("1", response);
        fileServiceImpl.downloadFiles(cdFiles, responseHeaderSet.getOutputStream());
    }

    @SneakyThrows
    private HttpServletResponse fileDownloadResponseHeaderSet(String fileName, HttpServletResponse response){
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        response.setHeader("Access-Control-Allow-Origin", "*");
        return response;
    }

    @RequestMapping(value = "/copy_or_cut", method = RequestMethod.POST)
    public R copyOrCutFile(@RequestParam("target_file") String targetFolder, @RequestParam("is_cut") Boolean isCut,@RequestBody List<CdFile> cdFiles){
        boolean b = fileServiceImpl.copyOrCutFile(cdFiles, isCut, targetFolder);
        return b ? R.ok():R.error().message("粘贴失败，可能存在同名文件");
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R list(){
        List<CdFile> list = fileServiceImpl.initFileList(null);
        return R.ok().data("list", list);
    }

    @SneakyThrows
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam(value = "filePath", required = false) String filePath){
        String decode = URLDecoder.decode(filePath, "UTF-8");
        List<CdFile> list = fileServiceImpl.initFileList(decode);
        int size = list.size();
        List<CdFile> collect = list.stream().skip((long) pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
        return R.ok().data("list", collect).data("total", size);
    }

    @SneakyThrows
    @RequestMapping(value = "/search_files", method = RequestMethod.GET)
    public R page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam(value = "filePath", required = false) String filePath, @RequestParam("searchContent") String searchContent){
        List<CdFile> list = fileServiceImpl.searchFiles(URLDecoder.decode(filePath, "UTF-8"), searchContent);
        int size = list.size();
        List<CdFile> collect = list.stream().skip((long) pageSize * (pageNum - 1)).limit(pageSize).collect(Collectors.toList());
        return R.ok().data("list", collect).data("total", size);
    }

    @RequestMapping(value = "/update_file_name", method = RequestMethod.POST)
    public R update(@RequestBody CdFile oldFile, @RequestParam("newFileName") String newFileName){
        boolean b = fileServiceImpl.setFileName(oldFile, newFileName);
        return b ? R.ok():R.error();
    }

    private final FileServiceImpl fileServiceImpl;

    public CdFileController(FileServiceImpl fileServiceImpl){
        this.fileServiceImpl = fileServiceImpl;
    }

}
